package charazay.tool.managers.cobjects;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import charazay.tool.cobjects.Player;
import charazay.tool.managers.files.FileManager;
import charazay.tool.managers.XML.PlayerFileContentHandler;
import charazay.tool.managers.cobjects.GenericManager;
import charazay.tool.misc.Session;

public class PlayerManager extends GenericManager {

	HashMap<Integer, Player> players = new HashMap();

	public PlayerManager() {

	}

	public HashMap getPlayers() {
		File player_repository = new File(FileManager.PLAYERS_DIR);
		String[] playerfiles_list = player_repository.list();
		if (playerfiles_list.length > 0) {
			XMLReader saxReader = null;
			try {
				saxReader = XMLReaderFactory
						.createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
				saxReader.setContentHandler(new PlayerFileContentHandler(
						Session.username, Session.password));
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			for (int i = 0; i < playerfiles_list.length; i++) {
				File playerfile = new File(FileManager.PLAYERS_DIR
						+ playerfiles_list[i]);

				try {
					saxReader.parse(playerfile.getAbsolutePath());
					Player player = ((PlayerFileContentHandler) saxReader
							.getContentHandler()).getPlayer();
					players.put(
							new Integer(player.getCharazay_id()),
							player);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		return players;
	}
	
	public Player getPlayerAt(Integer id_player) {
		return players.get(id_player);
	}

}
